

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;

import com.aios.action.AbstractAction;
import com.aios.entity.SystemUser;
import com.aios.exception.SessionNotExist;
import com.aios.service.impl.SystemUserServiceImpl;
import com.aios.util.SessionKey;

@Scope("prototype")
public class SignInAction extends AbstractAction {

	@Autowired
	private SystemUserServiceImpl systemUserServiceImpl;

	private static final long serialVersionUID = 1L;

	private SystemUser systemUser;

	public String showSigninForm() {
		return SUCCESS;
	}

	public String signIn() {
		try {

			if (systemUser == null) {
				addActionError(getText("system.user.signin.failed"));
				return INPUT;
			}
			
			validateSignIn();
			if (hasErrors()) {
				return INPUT;
			}

			systemUser = systemUserServiceImpl.signIn(systemUser.getEmail(),
					systemUser.getUserPassword());

			addSessionUserVariable(systemUser);
			return SUCCESS;
			
		} catch (Exception e) {
			e.printStackTrace();
			return SUCCESS;
		}
	}

	public String signOut() {

		try {
			if (verifySessionUser()) {
				removeSessionVariable(SessionKey.SESSION_USER);
			}
		} catch (SessionNotExist e) {
			e.printStackTrace();
			// logger
		}

		return SUCCESS;
	}

	private void validateSignIn() {
		if (systemUser.getEmail().isEmpty()) {
			addFieldError("systemUser.email",
					getText("system.user.email.empty"));
		}

		if (systemUser.getUserPassword().isEmpty()) {
			addFieldError("systemUser.userPassword",
					getText("system.user.password.empty"));
		}
	}

	public SystemUser getSystemUser() {
		return systemUser;
	}

	public void setSystemUser(SystemUser systemUser) {
		this.systemUser = systemUser;
	}

}
